<?php

/**
 * GoogleCheckoutController is the default controller for this application
 */
class GoogleCheckoutController extends CustomControllerBase {
	
	/**
	 * Constructor of index
	 */
	public function __construct() {
		parent::__construct ();
		// Set page name
		$this->setPageName ( 'google_checkout_handler' );
	}
	
	/**
	 * The "index" action is the default action for all controllers -- the
	 * landing page of the site.
	 *
	 * @return void
	 *
	 */
	public function indexAction() {
		//Set No Display
		$config = $this->settingsDataService->getGoogleCheckoutSettings ( $this->ownerId );
		if (isset ( $config ['merchantId'] ) && isset ( $config ['enable'] ) && $config ['enable'] == true) {
			$merchant_id = $config ['merchantId']; // Your Merchant ID
			$merchant_key = $config ['merchantKey']; // Your Merchant Key
			$server_type = $config ['server_type'];
			$currency = "USD"; // Need Update here
		}
		
		$Gresponse = new GoogleResponse ( $merchant_id, $merchant_key );
		$Grequest = new GoogleRequest ( $merchant_id, $merchant_key, $server_type, $currency );
		
		//Setup the log file
		$Gresponse->SetLogFiles ( GOOGLE_ERROR_LOG_FILE, GOOGLE_HANDLER_LOG_FILE, L_ALL );
		
		// Retrieve the XML sent in the HTTP POST request to the ResponseHandler
		$xml_response = isset ( $HTTP_RAW_POST_DATA ) ? $HTTP_RAW_POST_DATA : file_get_contents ( "php://input" );
		if (get_magic_quotes_gpc ()) {
			$xml_response = stripslashes ( $xml_response );
		}
		list ( $root, $data ) = $Gresponse->GetParsedXML ( $xml_response );
		$Gresponse->SetMerchantAuthentication ( $merchant_id, $merchant_key );
		
		$status = $Gresponse->HttpAuthentication ();
		if (! $status) {
			return false;
		}
		
		if ($root == "new-order-notification") {
			
			// Get Google order id
			$googleOrderId = $data [$root] ['google-order-number'] ['VALUE'];
			
			// Get order id
			$orderId = $data [$root] ['shopping-cart'] ['merchant-private-data'] ['merchant-order-id'] ['VALUE'];
			
			// Get customer id
			$customerId = $data [$root] ['shopping-cart'] ['merchant-private-data'] ['merchant-customer-id'] ['VALUE'];
			
			// Check order id, google id, customer id
			if (! empty ( $orderId ) && ! empty ( $googleOrderId ) && is_numeric ( $orderId ) && ! empty ( $customerId ) && is_numeric ( $customerId )) 

			{
				$customerOrderDataService = new CustomerOrderDataService ();
				$arrElement = array ();
				$arrElement ['id'] = intval ( $orderId );
				$arrElement ['customers_id'] = intval ( $customerId );
				$arrElement ['payment_method'] = PAYMENT_GOOGLECHECKOUT;
				$results = $customerOrderDataService->getItems ( $arrElement );
				if (count ( $results ) > 0 && ! empty ( $results [0] )) {
					
					// Update paygate order id
					$customerOrder = $results [0];
					$customerOrder->last_modified = date ( "Y-m-d H:i:s" );
					$customerOrder->paygate_order_id = $googleOrderId;
					$customerOrderDataService->update ( $customerOrder );
					
					// Add order history
					$orderStatusHistoryDataService = new OrderStatusHistoryDataService ();
					$orderHistory = $orderStatusHistoryDataService->beforeCreate ();
					$orderHistory->orders_id = $customerOrder->id;
					$orderHistory->date_added = date ( "Y-m-d H:i:s" );
					$orderHistory->comments = "";
					$orderHistory->orders_status = ORDER_STATUS_PENDING;
					$orderStatusHistoryDataService->create ( $orderHistory );
					
					// Empty cart
					$userCustomerBasketDataService = new UserCustomerBasketDataService ();
					$userCustomerBasketDataService->removeCart ( $customerOrder->customers_id, NULL );
				}
			}
			
			// reply to google
			$Gresponse->SendAck ();
		}
		
		if ($root == "refund-amount-notification") {
			// file_put_contents(dirname(__FILE__) . "/callback_log.log", "refund-amount-notification: " . time() . PHP_EOL, FILE_APPEND);
			

			// reply to google
			$Gresponse->SendAck ();
		}
		
		if ($root == "order-state-change-notification") {
			
			$new_financial_state = $data [$root] ['new-financial-order-state'] ['VALUE'];
			$new_fulfillment_order = $data [$root] ['new-fulfillment-order-state'] ['VALUE'];
			
			// Get Google order id
			$googleOrderId = $data [$root] ['google-order-number'] ['VALUE'];
			
			// Update status and insert order history
			switch ($new_fulfillment_order) {
				case 'PROCESSING' :
				case 'DELIVERED' :
				case 'WILL_NOT_DELIVER' :
					$customerOrderDataService = new CustomerOrderDataService ();
					$arrElement = array ();
					$arrElement ['paygate_order_id'] = $googleOrderId;
					$arrElement ['payment_method'] = PAYMENT_GOOGLECHECKOUT;
					$results = $customerOrderDataService->getItems ( $arrElement );
					if (count ( $results ) > 0 && ! empty ( $results [0] )) {
						$customerOrder = $results [0];
						$customerOrder->last_modified = date ( "Y-m-d H:i:s" );
						$orderStatusHistoryDataService = new OrderStatusHistoryDataService ();
						$orderHistory = $orderStatusHistoryDataService->beforeCreate ();
						$orderHistory->orders_id = $customerOrder->id;
						$orderHistory->date_added = date ( "Y-m-d H:i:s" );
						$orderHistory->comments = "";
						switch ($new_fulfillment_order) {
							/*
							case 'NEW': {
								break;
							}*/
							case 'PROCESSING' :
								$customerOrder->orders_status = ORDER_STATUS_PROCESSING;
								$orderHistory->orders_status = ORDER_STATUS_PROCESSING;
								break;
							case 'DELIVERED' :
								$customerOrder->orders_status = ORDER_STATUS_DELIVERED;
								$orderHistory->orders_status = ORDER_STATUS_DELIVERED;
								break;
							case 'WILL_NOT_DELIVER' :
								$customerOrder->orders_status = ORDER_STATUS_CANCELLED;
								$orderHistory->orders_status = ORDER_STATUS_CANCELLED;
								break;
						}
						$orderStatusHistoryDataService->create ( $orderHistory );
						$customerOrderDataService->update ( $customerOrder );
					}
					break;
			}
			
			/*
			switch($new_financial_state) {
				case 'REVIEWING': {
					break;
				}
				case 'CHARGEABLE': {
					//$Grequest->SendProcessOrder($data[$root]['google-order-number']['VALUE']);
					//$Grequest->SendChargeOrder($data[$root]['google-order-number']['VALUE'],'');
					break;
				}
				case 'CHARGING': {
					break;
				}
				case 'CHARGED': {
					break;
				}
				case 'PAYMENT_DECLINED': {
					break;
				}
				case 'CANCELLED': {
					break;
				}
				case 'CANCELLED_BY_GOOGLE': {
					//$Grequest->SendBuyerMessage($data[$root]['google-order-number']['VALUE'],
					//    "Sorry, your order is cancelled by Google", true);
					break;
				}
				default:
					break;
			}
			*/
			
			//file_put_contents(dirname(__FILE__) . "/callback_log.log", "$new_financial_state: " . time() . PHP_EOL, FILE_APPEND);
			

			$Gresponse->SendAck ();
		}
	
	}
}
